#include <stdio.h>
#include <sys/types.h>  
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/select.h>

#define N 128
int main(int argc, const char *argv[])
{

	int sockfd,accepfd;
	//int ret,ret1;
	char buf[N]={0};

	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(sockfd<0)
	{
		perror("err");
		exit(-1);
	}
	printf("sockfdok\n");

	struct sockaddr_in serveraddr;
	serveraddr.sin_family=AF_INET;
	serveraddr.sin_port=htons(atoi(argv[2]));
	serveraddr.sin_addr.s_addr=inet_addr(argv[1]);


	socklen_t addrlen =sizeof(serveraddr);

	struct sockaddr_in clientaddr;
	socklen_t clilen =sizeof(clientaddr);

	printf("bangding ok\n");


	if(bind(sockfd,(struct sockaddr *)&serveraddr,addrlen) < 0)
	{
		perror("hhhhh");
		exit(-1);
	}
	printf("bind ok\n");

	if(listen(sockfd,8)<0)
	{
		perror("listenerr");
		exit(-1);
	}
	printf("listen ok\n");


	fd_set readfds,tempfds;
	FD_ZERO(&readfds);
	FD_ZERO(&tempfds);

	FD_SET(0,&readfds);
	FD_SET(sockfd,&readfds);

	int maxfd,val,i;
	maxfd=sockfd;
	//	int recvbytes;
	//	int sendbytes;
	printf("ok\n");

	while(1)
	{
		tempfds=readfds;
		val=select(maxfd + 1,&tempfds,NULL,NULL,NULL);

		if(val < 0)
		{
			perror("select faile");
			exit(-1);
		}
		printf("val<0 ok\n");

		for(i=0;i<maxfd+1;i++)
		{
			if(FD_ISSET(i,&tempfds))
			{
				if(i == 0)
				{


					fgets(buf,sizeof(buf),stdin);
					buf[strlen(buf) - 1] = '\0';
					printf("buf:%s\n",buf);

				}else if(i == sockfd)

				{


					accepfd = accept(sockfd,(struct sockaddr *)&clientaddr,&clilen);
					if(accepfd<0)
					{
						perror("err");
						exit(-1);
					}
					printf("client ip = %s,port = %d\n",
							(char *)inet_ntoa(clientaddr.sin_addr),
							ntohs(clientaddr.sin_port));
					FD_SET(accepfd,&readfds);
					maxfd =(maxfd > accepfd)?maxfd:accepfd;

				}
				else
				{
					ssize_t sendbytes;
					if (buf[0] != 0)
					{
						send(i, buf, sizeof(buf), 0);
						bzero(buf, sizeof(buf));
					}
					ssize_t recvbytes;
					recvbytes = recv(i, buf, sizeof(buf), 0);
					if (recvbytes < 0)
					{
						FD_CLR(i, &readfds);
						close(i);
						perror("recv failed.");
						continue;
					}
					else if (0 == recvbytes)
					{
						printf("client %d exit\n", i);
						FD_CLR(i, &readfds);
						close(i);
					}
					else
					{
						printf("recv : %s\n", buf);
						bzero(buf, sizeof(buf));
					}
				}
			}
		}
	}



	return 0;
}
